Skip to main content
查利博客

160. Intersection of Two Linked Lists

Question Link: https://leetcode.com/problems/intersection-of-two-linked-lists/description/

Java Code #

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode ptrA, ptrB;
        ptrA = headA;
        ptrB = headB;

        while (ptrA != ptrB) {
            ptrA = ptrA.next;
            ptrB = ptrB.next;

            if(ptrA == ptrB)
                return ptrA;
            if (ptrA == null)
                ptrA = headB;
            if (ptrB == null)
                ptrB = headA;
        }

        return ptrA;
    }
}

C Code #

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
    struct ListNode *ptrA = headA;
    struct ListNode *ptrB = headB;

    while (ptrA != ptrB) {
        ptrA = ptrA->next;
        ptrB = ptrB->next;

        if (ptrA == ptrB)
            return ptrA;

        if (ptrA == NULL)
            ptrA = headB;
        if (ptrB == NULL)
            ptrB = headA;
    }

    return ptrA;
}